package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "套餐相关接口")
public class SetMealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    // 清除setmealCache名称下,所有的缓存数据
    @CacheEvict(value = "setmealCache", allEntries = true)
    @ApiOperation("新增套餐接口")
    public R saveSetmeal(@RequestBody SetmealDto setmealDto) {
        log.info("套餐信息： {}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功！");
    }

    /**
     * 套餐管理中 套餐分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    })
    public R pageQuerySetmeal(Integer page, Integer pageSize, String name) {

        //分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        // 查询条件：根据name 模糊查询
        setmealQueryWrapper.like(name != null, Setmeal::getName, name);

        //排序条件：根据更新时间降序排列
        setmealQueryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo, setmealQueryWrapper);

        //对桑拷贝
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");

        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map((one) -> {
            SetmealDto setmealDto = new SetmealDto();

            //对象拷贝
            BeanUtils.copyProperties(one, setmealDto);
            // 分类id
            Long categoryId = one.getCategoryId();
            // 更具分类id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //分类名
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    //清除setmealCache名称下,所有的缓存数据
    @CacheEvict(value = "setmealCache", allEntries = true)
    @ApiOperation(value = "删除套餐接口")
    public R deletesetmeal(@RequestParam List<Long> ids) {
        // java.util.List<java.lang.Long> --> public R delete(@RequestBody List<Long> ids) {}
        log.info("ids:{}", ids);
        setmealService.removeWitnDish(ids);
        return R.success("套餐数据删除成功！");
    }

    /**
     * 修改套餐状态（起售/停售）
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    //清除setmealCache名称下,所有的缓存数据
    @CacheEvict(value = "setmealCache", allEntries = true)
    @ApiOperation(value = "起售/停售套餐接口")
    public R updateStatus(@PathVariable Integer status,
                          @RequestParam List<Long> ids) {
        // update setmeal set status = ? where id in (1,2,3)
        // 方法一
        LambdaUpdateWrapper<Setmeal> setmealUpdateWrapper = new LambdaUpdateWrapper<>();
        setmealUpdateWrapper.in(Setmeal::getId, ids);
        setmealUpdateWrapper.set(Setmeal::getStatus, status);
        setmealService.update(setmealUpdateWrapper);
        // 方法二
        /*for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }*/
        // TODO update setmeal set status
        return R.success("修改成功!");
    }

    /**
     * 根据id查询套餐信息(修改时回显)
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据套餐id查询套餐数据")
    public R<Setmeal> getBySetmealId(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getBySetmealId(id);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    //清除setmealCache名称下,所有的缓存数据
    @CacheEvict(value = "setmealCache", allEntries = true)
    @ApiOperation(value = "修改套餐接口")
    public R updatesetmeal(@RequestBody SetmealDto setmealDto) {
        log.info(setmealDto.toString());
        setmealService.updatesetmeal(setmealDto);
        return R.success("修改套餐成功!");
    }


    /**
     * 根据套餐分类id查询该套餐分类下的套餐(前端首页菜品展示)
     * @param setmeal
     * @return
     */
    // 将套餐分类ID和套餐状态组合起来作为key

    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    @ApiOperation(value = "根据套餐分类id查询该套餐分类下的套餐")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        // select * from setmeal where category_id = ? and status = ? order by update_time

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }
}
